const jwt = require('jsonwebtoken');
const { promisify } = require('util');

const sign = promisify(jwt.sign);
const verify = promisify(jwt.verify);

/**
 * 生成JWT令牌
 * @param {Object} payload 载荷
 * @param {string} secret 密钥
 * @param {Object} options 选项
 * @returns {Promise<string>} JWT令牌
 */
const generateToken = async (payload, secret = process.env.JWT_SECRET, options = {}) => {
  const defaultOptions = {
    expiresIn: process.env.JWT_EXPIRES_IN || '7d'
  };
  
  const jwtOptions = { ...defaultOptions, ...options };
  
  return sign(payload, secret, jwtOptions);
};

/**
 * 验证JWT令牌
 * @param {string} token JWT令牌
 * @param {string} secret 密钥
 * @returns {Promise<Object>} 解码后的载荷
 */
const verifyToken = async (token, secret = process.env.JWT_SECRET) => {
  try {
    return await verify(token, secret);
  } catch (error) {
    throw new Error('无效的令牌');
  }
};

module.exports = {
  generateToken,
  verifyToken
};
